<template>
  <mt-popup v-model="popupVisible" position="right" :modal="false" class="store-choice">
    <div class="page">
      <div class="scroll-view">
        <customHeader v-if="!multipleChoice&&hasTotal" middleTitle="选择门店" @leftCallBack="popupHide"   :jsBridgeBack="false"/>
        <customHeader v-if="!multipleChoice&&!hasTotal" middleTitle="选择门店" @leftCallBack="back"   :jsBridgeBack="false"/>
        <customHeader
          v-if="multipleChoice"
          middleTitle="选择门店"
          @leftCallBack="back"
          rightTitle="确定"
          @rightCallBack="popupHide"
          :jsBridgeBack="false"
        />
        <searchBar @search="searchCallbck"/>
        <div class="scroll-ct page-body">
          <div class="store-choice-list">
            <div v-if="multipleChoice" class="item all" @click="choiceAll" selectName="全部门店">
              <div class="item-ct">
                <span :class="selectAllFlag?'list_select label':'list-wx label'">全部门店</span>
              </div>
            </div>
            <div v-if="hasTotal"  class="item all" @click="singleChoiceAll" selectName="全部门店">
              <div class="item-ct">
                <span :class="singleChoiceAllFlag?'list_select label':'list-wx label'">全部门店</span>
              </div>
            </div>
          </div>
          <div
            class="store-choice-list"
            v-for="(item,index) in listData"
            :key="index"
            v-show="item.visible"
          >
            <div class="head">{{item.head}}</div>
            <div
              class="item"
              @click="storeItemChoice(childitem.key,childitem.data.disabled)"
              v-for="(childitem,index) in item.children"
              :key="index"
            >
              <div
                :class="childitem.data.disabled?'item-ct disabled':'item-ct'"
                v-show="childitem.visible"
              >
                <span :class="childitem.select?'list_select label':'list-wx label'">
                  <template v-if="multipleChoice">
                    <i v-if="!childitem.select" class="zhk-list-wx"></i>
                    <i v-if="childitem.select" class="zhk-list_select"></i>
                  </template>
                  <span class="store-bage" v-if="childitem.level==4">M4</span>
                  <span>{{childitem.label}}</span>
                  <span v-if="childitem.data.tag" class="tag">{{childitem.data.tag}}</span>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </mt-popup>
</template>

<script>
import Vue from "vue";
import { Popup, Toast } from "mint-ui";
import customHeader from "../../components/header/header";
import searchBar from "../../components/searchBar/searchBar";
Vue.component(Popup.name, Popup);
export default {
  name: "StoreChoice",
  data() {
    return {
      listData: [],
      popupVisible: false,
      storeName: "选择门店",
      selectAllFlag: false,
      singleChoiceAllFlag: false,
      dataSource: [],
      currentSelect: this.current //用于点返回记录还原数据
    };
  },
  props: {
    multipleChoice: {
      type: Boolean,
      default: false
    },
    hasTotal: {
      type: Boolean,
      default: true
    },
    current: {
      type: Array,
      default: []
    },
    isReset: {
      default: false
    },

    //是否过滤掉其他状态门店，只显示审核通过的门店
    statusFilter: {
      type: Boolean,
      default: false
    },
    //是否过滤掉其他状态门店，只显示审核通过的门店
    reqUrl: {
      type: String,
    }
  },
  mounted() {
    this.getData(() => {
      this.reset();
      let selectArr = [];
      for (let city of this.listData) {
        for (let store of city.children) {
          if (store.select === true) {
            selectArr.push({ selectName: store.label, selectKey: store.key });
          }
        }
      }
      this.currentSelect = selectArr;
    });
  },
  methods: {
    searchCallbck(v) {
      if (v) {
        //有值搜索
        for (let city of this.listData) {
          let hasVisible = false;
          for (let store of city.children) {
            if (store.label.indexOf(v) !== -1) {
              store.visible = true;
              hasVisible = true;
            } else {
              store.visible = false;
            }
          }
          city.visible = hasVisible;
        }
      } else {
        //无值还原
        for (let city of this.listData) {
          city.visible = true;
          for (let store of city.children) {
            store.visible = true;
          }
        }
      }
    },
    closeOnly() {
      this.popupVisible = false;
    },
    //重置为全选
    reset() {
      if (this.multipleChoice) {
        this.selectAllFlag = true;
        for (let city of this.listData) {
          city.visible = true;
          for (let store of city.children) {
            store.visible = true;
            store.select = true;
          }
        }
      }
      if (!this.multipleChoice) {
        this.singleChoiceAllFlag = true;
      }
    },
    popupShow() {
      this.popupVisible = true;
    },
    //返回
    popupHide() {
      let selectArr = [];
      if (this.selectAllFlag || this.singleChoiceAllFlag) {
        this.storeName = "全部门店";
      } else {
        this.storeName = "选择门店";
      }

      const listData = this.listData;
      if (this.singleChoiceAllFlag) {
        selectArr.push({ selectName: "全部门店", selectKey: "all" });
      } else {
        for (let city of listData) {
          for (let store of city.children) {
            if (store.select === true) {
              selectArr.push({ selectName: store.label, selectKey: store.key });
              if (!this.multipleChoice) {
                this.storeName = store.label;
              }
            }
          }
        }
      }
      if (this.multipleChoice && selectArr.length == 0) {
        Toast("请选择门店");
        return;
      }
      this.$emit("listenToStoreSelect", selectArr, this.storeName);
      this.currentSelect = selectArr;
      this.popupVisible = false;
    },
    //返回（不传值）
    back() {
      this.listData = this.checkDataSource(this.dataSource, this.currentSelect);
      this.popupVisible = false;
    },
    //选择全部
    choiceAll() {
      const selectAllFlag = this.selectAllFlag;
      this.selectAllFlag = !selectAllFlag;
      for (let i = 0; i < this.listData.length; i++) {
        for (let j = 0; j < this.listData[i].children.length; j++) {
          this.listData[i].children[j].select = !selectAllFlag;
        }
      }
    },
    //单选选择全部
    singleChoiceAll() {
      this.singleChoiceAllFlag = true;

      for (let i = 0; i < this.listData.length; i++) {
        for (let j = 0; j < this.listData[i].children.length; j++) {
          this.listData[i].children[j].select = false;
        }
      }
      this.popupHide();
    },
    //门店选择
    storeItemChoice(key, disabled) {
      if (disabled) {
        return false;
      }
      const listData = this.listData;
      if (this.multipleChoice) {
        //多选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].key == key) {
              let flag = this.listData[i].children[j].select;
              this.listData[i].children[j].select = !flag;
            }
          }
        }
        //如果每一项都选中全部门店勾选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].select == false) {
              this.selectAllFlag = false;
              return;
            } else {
              this.selectAllFlag = true;
            }
          }
        }
      } else {
        this.singleChoiceAllFlag = false;
        //单选
        for (let i = 0; i < this.listData.length; i++) {
          for (let j = 0; j < this.listData[i].children.length; j++) {
            if (this.listData[i].children[j].key == key) {
              let flag = this.listData[i].children[j].select;
              this.listData[i].children[j].select = true;
            } else {
              this.listData[i].children[j].select = false;
            }
          }
        }
        this.popupHide();
      }
    },
    checkDataSource(data, currentSelect) {
      let shopList = [];
      let all = true;
      if (data != null && JSON.stringify(data) != "{}") {
        for (var cityName in data) {
          var childrenList = [];
          if (data[cityName] != null && data[cityName].length > 0) {
            for (var i = 0; i < data[cityName].length; i++) {
              //回显选中
              const isChecked = currentSelect.filter(item => {
                return item.selectKey === data[cityName][i].shopId;
              }).length;

              //状态筛选 审批中：1  审批驳回：3  的门店不显示
              if (
                this.statusFilter &&
                (data[cityName][i].auditStatus !== 1 &&
                  data[cityName][i].auditStatus !== 3)
              ) {
                if (isChecked) {
                  childrenList.push({
                    visible: true,
                    level: data[cityName][i].level,
                    key: data[cityName][i].shopId,
                    label: data[cityName][i].shopName,
                    select: true,
                    data: data[cityName][i]
                  });
                } else {
                  all = false;
                  childrenList.push({
                    visible: true,
                    level: data[cityName][i].level,
                    key: data[cityName][i].shopId,
                    label: data[cityName][i].shopName,
                    select: false,
                    data: data[cityName][i]
                  });
                }
              } else if (!this.statusFilter) {
                if (isChecked) {
                  childrenList.push({
                    visible: true,
                    level: data[cityName][i].level,
                    key: data[cityName][i].shopId,
                    label: data[cityName][i].shopName,
                    select: true,
                    data: data[cityName][i]
                  });
                } else {
                  childrenList.push({
                    visible: true,
                    level: data[cityName][i].level,
                    key: data[cityName][i].shopId,
                    label: data[cityName][i].shopName,
                    select: false,
                    data: data[cityName][i]
                  });
                }
              }
            }
          }
          childrenList.length > 0 &&
            shopList.push({
              head: cityName,
              children: childrenList,
              visible: true
            });
        }
      }
      this.selectAllFlag = all;
      return shopList;
    },
    getData(callBack) {
      const data=JSON.parse(sessionStorage.getItem("deviceStoreList"));
      this.dataSource = data;
      this.listData = this.checkDataSource(data, this.currentSelect);
      callBack && callBack();
      // const url =this.reqUrl?this.reqUrl:"/newapp/shop/getShopSelect.do"
      // this.ajax({
      //   url: url,
      //   type: "get",
      //   data: {},
      //   controlLoading: false
      // })
      //   .then(res => {
      //     if (res.success) {
      //       const data = res.resultObject;
      //       this.dataSource = data;
      //       this.listData = this.checkDataSource(data, this.currentSelect);
      //       callBack && callBack();
      //     }
      //   })
      //   .catch(function(err) {

      //   });
    }
  },
  components: {
    customHeader,
    searchBar
  },
  watch: {
    isReset(newVal, oldVal) {
      if (newVal) {
        this.reset();
        this.popupHide();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "StoreChoice";
</style>
